package javango.contrib.jquery;

import java.util.List;

import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Expression;
import org.hibernate.mapping.PersistentClass;

import com.google.inject.Inject;

import javango.contrib.hibernate.HibernateUtil;
import javango.contrib.hibernate.ModelDao;
import javango.contrib.hibernate.Pagination;
import javango.core.User;
import javango.http.HttpRequest;
import javango.http.HttpResponse;
import javango.http.SimpleHttpResponse;

public class JqueryViews {

	HibernateUtil hibernateUtil;
	
	@Inject
    public JqueryViews(HibernateUtil hibernateUtil) {
		super();
		this.hibernateUtil = hibernateUtil;
	}


	protected String getSearchProperty(User u, PersistentClass pc) { // throws NotAuthorizedException {
        Class<?> modelClass = pc.getMappedClass();
        Promptable p = (Promptable)modelClass.getAnnotation(Promptable.class);
        if (p == null) return null;

        if ("".equals(p.requiredRole())) { // no authority required
                return p.property();
        }

        if (u == null) {
//                throw new NotAuthorizedException();
        	return null;
        }

        if ("*".equals(p.requiredRole())) { // any authorized user
                         return p.property();
        }
        if (u.hasRole(p.requiredRole())) { // user has the role
                return p.property();
        }

        // throw new NotAuthorizedException();
        return null;

}


    public HttpResponse lookup(HttpRequest request, String model) throws Exception {
			Configuration cfg = hibernateUtil.getConfiguration();		
			PersistentClass pc = cfg.getClassMapping(model);
    	
            String queryString = request.getParameter("q");

            String searchProperty = getSearchProperty(request.getUser(), pc);
            if (searchProperty == null) {
                    return new SimpleHttpResponse("Unsupported class " + model + "|").setMimeType("text/plain");
            }
            ModelDao<?> dao = new ModelDao(hibernateUtil, pc.getMappedClass());
            Pagination p = new Pagination(new Long(100), null, null);  // TODO Make this configurable

            List<?> l = dao.filter(p)
                    .add(Expression.ilike(searchProperty, queryString + "%" ))
                    .list();

            StringBuilder b = new StringBuilder();
            for (Object o : l) {
                    b.append(String.format("%s|%s\n", o.toString(), dao.getPk(o)));
            }
            return new SimpleHttpResponse(b.toString()).setMimeType("text/plain");
    }

}
